package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    //注入
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;


    //tianjia
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        setmealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        this.setSetmealAndCheckgroup(setmealId,checkgroupIds);
        //将图片保存到Redis中
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);
        generateMobileStaticHtml();
    }
    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById4Detail(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            OutputStream fos = new FileOutputStream(outPutPath + "/" + htmlPageName);
            out = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
       Page<Setmeal> page = setmealDao.findPage(queryString);
        return new  PageResult(page.getTotal(),page.getResult());
    }

    //删除
    @Override
    public void delete(Integer id) {
        try {
            setmealDao.setSqlOff(0); //关闭外键检查
            setmealDao.deleteSetmealAndCheckgroup(id); //删除多表
            setmealDao.delete(id); //删除单表
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            setmealDao.setSqlOpen(1); //打开外键检查
        }
    }

    //查询套餐
    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> findSetmealAndcheckgroup(Integer id) {
        return setmealDao.findSetmealAndcheckgroup(id);
    }

    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        try {
            setmealDao.setSqlOff(0);
            //修改检查组基本信息，操作检查组t_checkgroup表
            setmealDao.edit(setmeal);
            //清理所有关联
            setmealDao.deleteAssocication(setmeal.getId());
            //重新建立当前检查组和检查项的关联关系
            Integer setmealId = setmeal.getId();
            this.setSetmealAndCheckgroup(setmealId,checkgroupIds);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            setmealDao.setSqlOpen(1);  //开启事务
        }
    }

    @Override
    public List<Setmeal> findAll() {
     return setmealDao.findAll();
    }

    @Override
    public Setmeal findSetmealById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

//    @Override
//    public Setmeal findByIdTwo(Integer id) {
//        return setmealDao.findByIdTwo(id);
//    }


    public void setSetmealAndCheckgroup(Integer setmealId,Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("setmealId", setmealId);
                map.put("checkgroupId", checkgroupId);
                setmealDao.setSetmealAndCheckGroup(map);
            }
        }
    }
}
